//
//  ImagePickerView.m
//  PickerManager
//
//  Created by iOS开发 on 2018/8/14.
//  Copyright © 2018年 iOS开发. All rights reserved.
//

#import "ImagePickerView.h"

static NSString * const AlbumAdd = @"AlbumAddBtn";
static const NSInteger CellInterval = 10;

@implementation ImageCollectionCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
        [self addSubview:_imageView];
    }
    return self;
}
@end


@interface ImagePickerView()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) NSMutableArray *imageViewArr;
@property (nonatomic, assign) NSInteger horizontalCount;
@property (nonatomic, assign) CGFloat CellWidth;
@end

@implementation ImagePickerView

- (void)dealloc {
    NSLog(@"释放%@", NSStringFromClass([self class]));
}

#pragma mark - init
- (instancetype)initWithFrame:(CGRect)frame AndHorizontalCount:(NSUInteger)horizontalCount {
    self = [super initWithFrame:frame];
    if (self) {
        _horizontalCount = horizontalCount;
        [self createView];
    }
    return self;
}

- (NSMutableArray *)imageViewArr {
    if (!_imageViewArr) {
        _imageViewArr = @[[UIImage imageNamed:AlbumAdd]].mutableCopy;
    }
    return _imageViewArr;
}

- (NSInteger)maxCount {
    if (!_maxCount) {
        _maxCount = 9;
    }
    return _maxCount;
}

- (void)createView {
    _CellWidth = (self.frame.size.width - ((_horizontalCount + 1) * CellInterval)) / _horizontalCount;
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, _CellWidth + CellInterval * 2);
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = CellInterval;
    flowLayout.minimumInteritemSpacing = CellInterval;
    flowLayout.itemSize = CGSizeMake(_CellWidth, _CellWidth);
    flowLayout.sectionInset = UIEdgeInsetsMake(CellInterval, CellInterval - 1, CellInterval, CellInterval - 1);
    
    _collection = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
    _collection.backgroundColor = [UIColor yellowColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.showsVerticalScrollIndicator = NO;
    _collection.showsHorizontalScrollIndicator = NO;
    _collection.scrollEnabled = NO;
    [self addSubview:_collection];
    
    [_collection registerClass:[ImageCollectionCell class] forCellWithReuseIdentifier:@"imageCell"];
}



#pragma mark - collectionDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imageViewArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ImageCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];
    
    cell.imageView.image = self.imageViewArr[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ImageCollectionCell *cell = (ImageCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    if ([self judgeImageIsEqualAddImage:cell.imageView]) {
        // 添加图片
        if ([self.delegate respondsToSelector:@selector(pushToPicker)]) {
            [self.delegate pushToPicker];
        }
    } else {
        // 点击查看图片
        if ([self.delegate respondsToSelector:@selector(checkImageWithIndex:withPhotos:)]) {
            [self.delegate checkImageWithIndex:indexPath withPhotos:[self PhotosRemovedAddImage:self.imageViewArr]];
        }
    }
}

// 更新图片
- (void)updatePhotos:(NSArray *)imageArray {
    [self.imageViewArr removeAllObjects];
    
    if (imageArray.count >= self.maxCount) {
        [self.imageViewArr addObjectsFromArray:[imageArray subarrayWithRange:NSMakeRange(0, self.maxCount)]];
    } else {
        [self.imageViewArr addObjectsFromArray:imageArray];
        [self.imageViewArr addObject:[UIImage imageNamed:AlbumAdd]];
    }
    [self changeFrame:self.imageViewArr.count];
    [UIView animateWithDuration:0 animations:^{
        [self.collection performBatchUpdates:^{
            [self.collection reloadSections:[NSIndexSet indexSetWithIndex:0]];
        } completion:nil];
    }];
}
// 添加拍摄图片
- (void)addCameraImage:(UIImage *)image {
    [self.imageViewArr removeLastObject];
    [self.imageViewArr addObject:image];
    if (self.imageViewArr.count < self.maxCount) {
        [self.imageViewArr addObject:[UIImage imageNamed:AlbumAdd]];
    }
    [self changeFrame:self.imageViewArr.count];
    [UIView animateWithDuration:0 animations:^{
        [self.collection performBatchUpdates:^{
            [self.collection reloadSections:[NSIndexSet indexSetWithIndex:0]];
        } completion:nil];
    }];

}

// 更新尺寸
- (void)changeFrame:(NSInteger)count {
    NSInteger verticalCount = count / _horizontalCount;
    if (count % _horizontalCount > 0) {
        verticalCount += 1;
    }
    
    [UIView animateWithDuration:.2f animations:^{
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, (self.CellWidth * verticalCount) + (CellInterval * (verticalCount + 1)));
        self.collection.frame = self.bounds;
    }];
}


// 判断图片是否跟添加图片相等
- (BOOL)judgeImageIsEqualAddImage:(UIImageView *)imageView {
    UIImageView *AddImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:AlbumAdd]];
    NSData *addData = UIImagePNGRepresentation(AddImageView.image);
    NSData *data = UIImagePNGRepresentation(imageView.image);
    
    if ([addData isEqual:data]) {
        // 两个UIimage相同
        return YES;
    } else { 
        // 两个UIImage不相同
        return NO;
    }
}

// 移除添加图片
- (NSMutableArray *)PhotosRemovedAddImage:(NSMutableArray *)imageArr {
    NSMutableArray *imageNoAddArr = [NSMutableArray arrayWithArray:imageArr];
    UIImage *image = [UIImage imageNamed:AlbumAdd];
    if ([imageArr containsObject:image]) {
        [imageNoAddArr removeObject:image];
    }
    return imageNoAddArr;
}

// 获取cell位置
- (CGRect)getCellPositionWithIndex:(NSIndexPath *)index inView:(UIView *)view {

    ImageCollectionCell *cell = (ImageCollectionCell *)[self.collection cellForItemAtIndexPath:index];
    CGRect rectIncollection = [self.collection convertRect:cell.frame toView:self.collection];
    CGRect rect = [self.collection convertRect:rectIncollection toView:[[self.collection superview] superview]];
    
    return rect;
}

@end
